<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\components\sms;

use Yii;
use yii\base\Component;
use yii\di\Instance;
use yii\web\View;
use yii\base\ViewContextInterface;

/**
 * 短信组件
 * For example:
 * ```php
 * // 发送登录验证码
 * Yii::$app->sms->createTemplate('login/index', ['smsCode' => Num::random()])->send(['mobile' => '15090321541'], 'order', 1501); // 返回: true|错误提示
 *
 * ```
 * @property-read string $smsContent 短信内容
 * @author cleverstone
 * @since ym2.0
 */
class SMS extends Component implements ViewContextInterface
{
    /**
     * @var SmsSenderInterface 短信发送驱动
     */
    public $sender;

    /**
     * @var string 短信签名
     */
    public $smsSign;

    /**
     * @var string 模板内容
     */
    private $_templateContent;

    /**
     * @var View 视图实例
     */
    private $_view;

    /**
     * {{@inheritdoc}}
     */
    public function init()
    {
        $this->sender = Instance::ensure($this->sender, SmsSenderInterface::class);
        $this->_view = Yii::$app->view;
    }

    /**
     * 创建模板内容
     * @param string $viewPath 模板
     * @param array $params 参数
     * @return $this
     */
    public function createTemplate($viewPath, $params = [])
    {
        $this->_templateContent = $this->_view->render($viewPath, $params, $this);
        return $this;
    }

    /**
     * 发送短信
     * @param array $params 发送参数
     * @param string $businessType 业务类型
     * @param int $businessID 业务ID
     * @return string|true
     */
    public function send(array $params, $businessType, $businessID)
    {
        return $this->sender->run($this->_templateContent, $params, $businessType, $businessID);
    }

    /**
     * 获取短信内容
     * @return string
     */
    public function getSmsContent()
    {
        return $this->_templateContent;
    }

    /**
     * {{@inheritdoc}}
     */
    public function getViewPath()
    {
        return __DIR__ . '/template';
    }
}